import React, {useEffect, useState} from "react";
import {Dimensions, ScrollView, StyleSheet, Text, TouchableHighlight, View} from "react-native";
import {SvgXml} from "react-native-svg";
import {addSvgXml, arrowRightSvgXml} from "../libs/svgXml";
import {cs, getBackgroundColor} from "./CommandCss/commandCss";
import {useFocusEffect} from "@react-navigation/native";
import {
    addressBookType,
    getAddressBook,
    getAddressBookNameList,
    getChainBaseByChainID,
    nowWallet
} from "./smartxL2Libs/L2_Data";
import {BottomSheet} from "react-native-elements/dist/bottomSheet/BottomSheet";
import SimpleToast from "react-native-simple-toast";

const {width,height,scale} = Dimensions.get("window");

const L2_AddressBookView = ({navigation,route}:any) => {
    const [from,setFrom] = useState(route.params?.from || 'transfer')
    const [addressBookList,setAddressBookList] = useState([]);
    //显示这个好友的地址
    const [showAddressList,setShowAddressList] = useState(false)
    //显示该链的地址
    const [addressList,setAddressList] = useState([{chainID:"",name:"",address:""}])
    //选中的item
    const [selectedItem,setSelectedItem] = useState(false)
    useEffect(()=>{
        navigation.setOptions({
            title:"地址簿"
        })
    },[])
    useFocusEffect(
        React.useCallback(() => {
            console.log("刷新页面")
            initDate()
        },[])
    );
    const initDate = async () => {
        let nameList = await getAddressBookNameList();
        let addressBookListTemp:addressBookType[] = [];
        for(let i = 0 ; i < nameList.length ; i++)
        {
            let addressBookTemp = await getAddressBook(nameList[i])
            addressBookTemp.chainNameList = [];
            for(let j = 0 ; j < addressBookTemp.chainIDList.length ; j++)
            {
                let chainName = await getChainNameById(addressBookTemp.chainIDList[j]);
                if(chainName)
                {
                    addressBookTemp.chainNameList.push(chainName)
                }
            }
            addressBookListTemp.push(addressBookTemp)
        }
        addressBookListTemp.sort(function(a,b){return a.timestamp-b.timestamp})
        console.log(`addressBookListTemp`,addressBookListTemp)
        setAddressBookList(addressBookListTemp)
    }
    const getChainNameById = async (chainID: string) => {
        let chainBase = await getChainBaseByChainID(chainID);
        if(chainBase)
        {
            return chainBase.name
        }
        return ""
    }
    const toL2_AddressBookAddView_edit = (item:any) => {
        if(!selectedItem && !item)
        {
            return;
        }
        let data = item || selectedItem;
        navigation.navigate(`L2_AddressBookAddView`,{type:true,name:data.name,remark:data.remark,addressList:data.bookAddressList})
    }
    const getAddressList = (item:any) => {
        let list = [...item.bookAddressList];
        let listNew = []
        for (let i = 0 ; i < list.length ; i++)
        {
            if(list[i].chainID === nowWallet.chainID)
            {
                listNew.push(list[i])
            }
        }
        if(listNew.length === 0)
        {
            setAddressList([])
            SimpleToast.show("该联系人没有钱包地址");
            return
        }
        console.log(`setAddressList`,listNew)
        setAddressList(listNew)
    }
    return (
        <View style={styles.container}>
            <ScrollView style={[cs.w_100,cs.h_100,cs.pr10]} contentContainerStyle={[cs.w_100,cs.pr10]} showsVerticalScrollIndicator={false}>
                {
                    addressBookList.length?
                        addressBookList.map((item:any,index) => (
                            <TouchableHighlight
                                underlayColor={"transparent"}
                                style={styles.itemContainer}
                                onPress={()=>{
                                    if(from !== 'transfer')
                                    {
                                        toL2_AddressBookAddView_edit(item)
                                        return;
                                    }
                                    getAddressList(item)
                                    setSelectedItem(item)
                                    setShowAddressList(true)
                            }} key={`addressBookList_${index}`}>
                                <View style={[cs.w_100,cs.fdRow,cs.jsb,cs.ac]}>
                                    <View style={[styles.itemInfoContainer,cs.w_100]}>
                                        <Text numberOfLines={1} style={[{color:"#6c6c6c"}]}>{item.name} {item.remark?`(${item.remark})`:""}</Text>
                                        <View style={[cs.fdRow,cs.ac,cs.pt5,{minHeight:30}]}>
                                            {
                                                item.chainNameList.map((item:string,indexTemp:number) => (
                                                    <Text key={`chainNameList_${indexTemp}`} style={[cs.borderRadioHalf, getBackgroundColor(indexTemp), cs.pl10, cs.pr10, cs.c_w, cs.mr5]}>{item}</Text>
                                                ))
                                            }
                                        </View>
                                    </View>
                                    <SvgXml xml={arrowRightSvgXml("#8d8d8d")} width={20} height={20}/>
                                </View>
                            </TouchableHighlight>
                        )):null
                }
            </ScrollView>
            <Text style={[
                cs.b20,cs.p10,cs.pl20,cs.pr20,
                cs.p_abs,cs.ta_c,cs.tav_c,
                cs.borderRadioHalf,getBackgroundColor(0),
                cs.c_w,cs.fs_13,cs.ls_half_0
            ]} onPress={()=>{
                navigation.navigate(`L2_AddressBookAddView`)

            }}>
                新建联系人
            </Text>

            <BottomSheet
                modalProps={{animationType:"fade"}}
                isVisible={showAddressList}
            >
                <View style={{width:width,height:height,backgroundColor: 'rgba(0.5, 0.25, 0, 0.2)'}}>
                    <TouchableHighlight underlayColor={"transparent"}
                                        style={[cs.f1,cs.w_100]}
                                        onPress={()=>{
                                            setSelectedItem(false)
                                            setShowAddressList(false)
                                        }}>
                        <View style={cs.f1}/>
                    </TouchableHighlight>
                    <View style={[cs.w_100,{height:45},cs.ac,cs.jc]}>
                        <Text style={[cs.fs_14,cs.ta_c,cs.w_100,cs.bgc_w,cs.tav_c,{height:45,borderBottomColor:"#f0f0f0"},cs.bbw_2s]}>请选择地址</Text>
                        <SvgXml onPress={()=>{
                            setSelectedItem(false)
                            setShowAddressList(false)
                            toL2_AddressBookAddView_edit()
                        }} xml={addSvgXml('black')} width={30} height={30} style={[cs.p_abs,cs.r5,cs.t_half(30)]}/>
                    </View>
                    <View style={[cs.w_100,cs.bgc_w,{height: addressList.length*45,maxHeight:height*0.7}]}>
                        <ScrollView style={[cs.w_100,cs.bgc_b,{minHeight:0}]} contentContainerStyle={[cs.w_100,{minHeight:0}]}>
                            {
                                addressList.length?
                                    addressList.map((item,index)=>(
                                        <Text style={[cs.fs_14,cs.ta_c,cs.w_100,cs.bgc_w,cs.tav_c,{height:45}]}
                                              onPress={()=>{
                                                  setSelectedItem(false)
                                                  setShowAddressList(false)
                                                  navigation.navigate("L2_transfer")
                                                  navigation.replace("L2_transfer",{receiver:item.address});
                                              }}
                                              key={`chainList_${index}`}
                                        >{item.address.slice(0,19)}...{item.address.slice(-18)}</Text>
                                    )):null
                            }
                        </ScrollView>
                    </View>
                    <View style={[cs.w_100,{height:7,backgroundColor:"#f5f6f8"}]}/>
                    <Text style={[cs.fs_14,cs.ta_c,cs.w_100,cs.bgc_w,cs.tav_c,{height:45}]}
                          onPress={()=>{
                              setSelectedItem(false)
                              setShowAddressList(false)
                          }}
                    >取消</Text>
                </View>
            </BottomSheet>
        </View>
    )
}
const styles = StyleSheet.create({
    container: {
        flex: 1,
        width: width,
        alignItems: "center",
        flexDirection: "column",
        paddingLeft: 20,
        paddingRight: 0,
        paddingTop:10,
        backgroundColor: "white"
    },
    itemContainer:{
        flexDirection:"row",
        alignItems:"center",
        justifyContent:"space-between",
        width:"100%",
        paddingRight:10,
        borderBottomWidth:3/scale,
        borderBottomColor:"#ececec"
    },
    itemInfoContainer:{
        paddingTop:5,
        paddingBottom:5,
    },
})
export default L2_AddressBookView;


